package com.leemz.ch2.jdbc.thirdedition;

import com.leemz.ch2.jdbc.entity.Student;
import com.leemz.ch2.jdbc.inter.IRowMapper;
import com.leemz.ch2.jdbc.inter.impl.StudentRowMapper;
import com.leemz.ch2.jdbc.util.JdbcTemplate;

import java.sql.ResultSet;
import java.util.List;

/**
 * 第三版，通过template模板走统一方法调用
 */
public class StudentServiceThird {
    public void save(Student student) {
        String sql = "insert into t_student(name, age) values(?,?)";
        Object[] params = new Object[]{student.getName(), student.getAge()};
        JdbcTemplate.update(sql, params);
    }

    public void delete(int id) {
        String sql = "delete from t_student where id=?";
        Object[] params = new Object[] {id};
        JdbcTemplate.update(sql, params);
    }

    public void update(Student student) {
        String sql = "update t_student set name=?, age=? where id=?";
        Object[] params = new Object[]{student.getName(), student.getAge(), student.getId()};
        JdbcTemplate.update(sql, params);
    }

    public Student get(int id) {
        String sql = "select * from t_student where id=?";
        List<Student> students = JdbcTemplate.query(sql, new StudentRowMapper(), id);
        return students.size() > 0 ? students.get(0) : null;
    }

    public List<Student> list() {
        String sql = "select * from t_student";
        List<Student> list = JdbcTemplate.query(sql, new StudentRowMapper());
        return list;
    }

    public int getCount() {
        String sql = "select count(*) total from t_student";
        int total = JdbcTemplate.query(sql, new IRowMapper<Integer>() {
            @Override
            public Integer handleResult(ResultSet resultSet) throws Exception {
                int total = 0;
                if(resultSet.next()) {
                    total = resultSet.getInt("total");
                }
                return total;
            }
        });
        return total;
    }
}
